package com.ahuan.aspect;

import com.ahuan.domain.GoodLog;
import com.ahuan.domain.UserAction;
import com.ahuan.mapper.GoodLogMapper;
import com.ahuan.mapper.UserActionMapper;
import com.ahuan.utils.JsonUtil;
import com.ahuan.utils.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.builder.BuilderException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.Month;
import java.util.Date;

@Slf4j
@Aspect
@Component
public class RequestLoggingAspect {


    private String requestMethod;


    @Before("execution(* com.ahuan.controller.*.*(..))")
    public void logBefore(JoinPoint joinPoint) {
        //获取请求参数
        Object[] methodArgs = joinPoint.getArgs();
        for (Object arg : methodArgs) {
            if (arg instanceof HttpServletRequest) {
                HttpServletRequest request = (HttpServletRequest) arg;
                // 获取请求方式
                this.requestMethod = request.getMethod();
                break;
            }
        }

    }

//    @After("execution(* com.ahuan.controller.*.*(..))")
//    public void logAfter(JoinPoint joinPoint) {
//        String methodName = joinPoint.getSignature().getName();
//        String className = joinPoint.getTarget().getClass().getSimpleName();
//        String requestMethod = joinPoint.getSignature().toShortString();
//
//        log.info("Request: {} - {} - Method: {} - Completed", className, methodName, requestMethod);
//    }


    @Autowired
    GoodLogMapper goodLogMapper;

    @Autowired
    UserActionMapper userActionMapper;


    @Around("execution(* com.ahuan.controller.*.*(..))")
    public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取request参数
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        // 获取请求地址
        String ipAddr = getRemoteHost(request);
        String requestUrl = request.getRequestURL().toString();


        // 获取请求类名
        String className = joinPoint.getTarget().getClass().getSimpleName();
        // 获取请求方法名
        String requestMethod = joinPoint.getSignature().toShortString();
        // 获取请求参数（request 和 response）
        Object[] methodArgs = joinPoint.getArgs();
        // 获取请求方式
        String requestMethodStored = request.getMethod();

        // 计算请求时间
        long startTime = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long endTime = System.currentTimeMillis();
        long elapsedTime = endTime - startTime;


        //记录日志
        log.info("请求控制器和请求方式: {} - {} - 请求地址：{} - 请求方法: {} - 请求参数：{} - 执行时间: {} ms", className, requestMethodStored, requestUrl, requestMethod, methodArgs, elapsedTime);


        if ("http://localhost:8080/api/Goods/ruku".equals(requestUrl)) {
            String num = request.getParameter("num");
            System.out.println("-------------" + num);
            GoodLog goodLog = new GoodLog();
            goodLog.setUserId(Long.parseLong(MDC.get("userId")));
            goodLog.setUsername(MDC.get("userName"));
            goodLog.setNum(Integer.parseInt(num));
            goodLog.setTableName("goods_log_" + TimeUtil.getTime());

            Integer insert = goodLogMapper.insert(goodLog);

            if (insert > 0) {
                log.info("日志记录成功");
            } else {
                log.info("日志记录失败");
                throw new BuilderException("出入库日志记录失败");
            }
        }


        return result;
    }

    private String getRemoteHost(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }

}
